#!/usr/bin/env python
#-*- coding: utf-8 -*-
# Copyright 2008 klen


""" Models for boardgames web-emulator for boardgames.leprosorium.ru """


import stuff
from google.appengine.ext 				import db
from google.appengine.api				import users


class Game(db.Model):
    """ Represents a single game """

    type = db.IntegerProperty(      required=True)
    created = db.DateTimeProperty(  auto_now_add=True)
    updated = db.DateTimeProperty(  auto_now=True)
    archived = db.BooleanProperty(  default=False)

    @staticmethod
    def get_current_user_games():
        """ Returns the games that the current user has access to. """
        return Game.get_user_games(users.get_current_user())

    @staticmethod
    def get_user_games(user):
        """ Returns the games that the given user has access to."""
        if not user: return []
        memberships = db.Query(GameMember).filter('user =', user)
        return [m.game for m in memberships]

    def has_current_user(self):
        """ Проверка на участие текущего пользователя в игре  """

        return self.has_user(users.get_current_user())

    def has_user(self, user):
        """ Проверка на участие пользователя в игре  """

        if not user: return False
        return user in self.get_users()

    def get_users(self):
        """ Метод возвращает пользователей в игре """

        memberships = db.Query(GameMember).filter('game =', self)
        return [m.user for m in memberships]

    def get_log(self):
        """ Return game log """

        return db.Query(GameLog).filter('game =', self)

    def get_begin(self):
        """ Возвращает истину в случае начала игры """

        return self.get_log().key()

    def get_box(self):
        """ Возвращает тип игры """

        return stuff.GAME_BOXES[self.type]



class GameMember(db.Model):
    """ Игры к пользователям """

    game = db.Reference(Game, required=True)
    user = db.UserProperty(required=True)


class GameLog(db.Model):
    """ Модель игрового лога """

    game = db.Reference( Game, required=True )
    user = db.UserProperty(required=True)
    date = db.DateTimeProperty( auto_now_add=True )
    type = db.IntegerProperty( required=True )
    system = db.BooleanProperty( default=True )
    message = db.StringProperty()

